#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include "threadPool.h"

// 任务结构体
typedef struct Task{
    void (*function)(void* arg);
    void* arg;
}Task;

// 线程池结构体
struct ThreadPool{
    // 任务队列
    Task* taskQ;
    int queueCapacity;  // 容量
    int queueSize;      // 当前任务个数
    int queueFront;     // 队头 -> 取数据
    int queueRear;      // 队尾 -> 放数据

    pthread_t managerID;    // 管理者线程ID
    pthread_t *threadIDs;   // 工作的线程ID
    int minNum;             // 最小线程数量
    int maxNum;             // 最大线程数量
    int busyNum;            // 忙的线程的个数
    int liveNum;            // 存活的线程的个数
    int exitNum;            // 要销毁的线程个数
    pthread_mutex_t mutexPool;  // 锁整个的线程池
    pthread_mutex_t mutexBusy;  // 锁busyNum变量
    pthread_cond_t notFull;     // 任务队列是不是满了
    pthread_cond_t notEmpty;    // 任务队列是不是空了

    int shutdown;           // 是不是要销毁线程池, 销毁为1, 不销毁为0
};

const int NUMBER = 2;  // 管理者线程 每次添加2个工作线程

ThreadPool* threadPoolCreate(int min, int max, int queueSize){
    ThreadPool* pool = (ThreadPool*)malloc(sizeof(ThreadPool));
    do {
        if (pool == NULL){
            printf("malloc threadpool fail...\n");
            break;
        }

        pool->threadIDs = (pthread_t*)malloc(sizeof(pthread_t) * max);
        if (pool->threadIDs == NULL){
            printf("malloc threadIDs fail...\n");
            break;
        }
        memset(pool->threadIDs, 0, sizeof(pthread_t) * max);
        pool->minNum = min;
        pool->maxNum = max;
        pool->busyNum = 0;
        pool->liveNum = min;    // 和最小个数相等
        pool->exitNum = 0;

        if (pthread_mutex_init(&pool->mutexPool, NULL) != 0 || pthread_mutex_init(&pool->mutexBusy, NULL) != 0 ||
            pthread_cond_init(&pool->notEmpty, NULL) != 0 || pthread_cond_init(&pool->notFull, NULL) != 0)
        {
            printf("mutex or condition init fail...\n");
            break;
        }

        // 任务队列
        pool->taskQ = (Task*)malloc(sizeof(Task) * queueSize);
        pool->queueCapacity = queueSize;
        pool->queueSize = 0;
        pool->queueFront = 0;
        pool->queueRear = 0;

        pool->shutdown = 0;  // 不销毁为0

        // 创建线程
        pthread_create(&pool->managerID, NULL, manager, pool);  // 创建管理者线程

        for (int i = 0; i < min; ++i){  // 创建工作线程
            pthread_create(&pool->threadIDs[i], NULL, worker, pool);
        }

        return pool;
    } while (0);

    // 释放资源
    if (pool && pool->threadIDs) free(pool->threadIDs);
    if (pool && pool->taskQ) free(pool->taskQ);
    if (pool) free(pool);

    return NULL;
}

int threadPoolDestroy(ThreadPool* pool){
    if (pool == NULL){
        return -1;
    }

    // 关闭线程池
    pool->shutdown = 1; 

    // 关闭线程池pool->shutdown = 1,管理者线程就退出while循环了,然后就退出了;
    // 阻塞回收管理者线程
    pthread_join(pool->managerID, NULL);

    // 唤醒阻塞的消费者线程
    // 线程就会继续向下执行,调用threadExit()函数
    for (int i = 0; i < pool->liveNum; ++i){
        pthread_cond_signal(&pool->notEmpty);
    }

    // 释放堆内存
    if (pool->taskQ){
        free(pool->taskQ);
    }

    if (pool->threadIDs){
        free(pool->threadIDs);
    }

    pthread_mutex_destroy(&pool->mutexPool);
    pthread_mutex_destroy(&pool->mutexBusy);
    pthread_cond_destroy(&pool->notEmpty);
    pthread_cond_destroy(&pool->notFull);

    free(pool);
    pool = NULL;

    return 0;
}


void threadPoolAdd(ThreadPool* pool, void(*func)(void*), void* arg){
    pthread_mutex_lock(&pool->mutexPool);
    while (pool->queueSize == pool->queueCapacity && !pool->shutdown){
        // 当线程池任务队列满了, 阻塞生产者线程
        pthread_cond_wait(&pool->notFull, &pool->mutexPool);
    }
    if (pool->shutdown){
        pthread_mutex_unlock(&pool->mutexPool);
        return;
    }

    // 添加任务
    pool->taskQ[pool->queueRear].function = func;
    pool->taskQ[pool->queueRear].arg = arg;
    pool->queueRear = (pool->queueRear + 1) % pool->queueCapacity;  // 环形
    pool->queueSize++;

    pthread_cond_signal(&pool->notEmpty);  // 唤醒工作线程
    pthread_mutex_unlock(&pool->mutexPool);
}

int threadPoolBusyNum(ThreadPool* pool){
    pthread_mutex_lock(&pool->mutexBusy);
    int busyNum = pool->busyNum;
    pthread_mutex_unlock(&pool->mutexBusy);
    return busyNum;
}

int threadPoolAliveNum(ThreadPool* pool){
    pthread_mutex_lock(&pool->mutexPool);
    int aliveNum = pool->liveNum;
    pthread_mutex_unlock(&pool->mutexPool);
    return aliveNum;
}

void* worker(void* arg){  // 工作线程
    ThreadPool* pool = (ThreadPool*)arg;

    while (1){ 
        pthread_mutex_lock(&pool->mutexPool);  // 整个线程池加锁
        // 当前任务队列是否为空
        // 使用while的作用:比如有10个线程被唤醒了,其中有一个判定任务队列不为空,就去工作;然后任务队列就为空,
        //                其他线程再回来判定的时候,任务队列为空,就会继续阻塞等待条件变量上;
        while (pool->queueSize == 0 && !pool->shutdown){  
            // 阻塞工作线程
            // 当任务队列不为空,通过 pool->notEmpty 把线程唤醒
            pthread_cond_wait(&pool->notEmpty, &pool->mutexPool);

            // 判断是不是要销毁线程(管理者线程里让工作线程自杀部分,每次自杀2个)
            if (pool->exitNum > 0){
                pool->exitNum--;
                
                // 如果满足条件就可以退出,否则不能; 
                if (pool->liveNum > pool->minNum){
                    pool->liveNum--;
                    // 当唤醒的时候已经加锁了,所以退出之前需要解锁,不然死锁了;
                    pthread_mutex_unlock(&pool->mutexPool);
                    threadExit(pool);
                }
            }
        }

        // 判断线程池是否被关闭了
        if (pool->shutdown){
            pthread_mutex_unlock(&pool->mutexPool);
            threadExit(pool);
        }

        // 从任务队列中取出一个任务
        Task task;
        task.function = pool->taskQ[pool->queueFront].function;
        task.arg = pool->taskQ[pool->queueFront].arg;
        // 移动头结点
        pool->queueFront = (pool->queueFront + 1) % pool->queueCapacity;
        pool->queueSize--;

        // 解锁
        pthread_cond_signal(&pool->notFull);  // 消费了任务, 唤醒生产者线程 --> threadPoolAdd()
        pthread_mutex_unlock(&pool->mutexPool);

        printf("thread %ld start working...\n", pthread_self());
        // 当线程工作时忙线程+1,但是其他线程也可能在忙,所以需要给busyNum加锁
        pthread_mutex_lock(&pool->mutexBusy);
        pool->busyNum++;
        pthread_mutex_unlock(&pool->mutexBusy);

         // 执行任务
        task.function(task.arg); 
        free(task.arg);
        task.arg = NULL;

        printf("thread %ld end working...\n", pthread_self());
        // 线程结束工作
        pthread_mutex_lock(&pool->mutexBusy);
        pool->busyNum--;
        pthread_mutex_unlock(&pool->mutexBusy);
    }
    return NULL;
}

// 管理者线程: 对当前工作线程的个数进行调节; 
void* manager(void* arg){  
    ThreadPool* pool = (ThreadPool*)arg;
    while (!pool->shutdown){
        // 每隔3s检测一次
        sleep(3);

        // 取出线程池中任务的数量和当前线程的数量
        pthread_mutex_lock(&pool->mutexPool);
        int queueSize = pool->queueSize;
        int liveNum = pool->liveNum;
        pthread_mutex_unlock(&pool->mutexPool);

        // 取出忙的线程的数量
        pthread_mutex_lock(&pool->mutexBusy);
        int busyNum = pool->busyNum;
        pthread_mutex_unlock(&pool->mutexBusy);

        // 添加线程
        // 添加规则:任务的个数>存活的线程个数 && 存活的线程数<最大线程数
        if (queueSize > liveNum && liveNum < pool->maxNum){
            pthread_mutex_lock(&pool->mutexPool);  // liveNum、maxNum等是共享变量,需要加锁
            int counter = 0;  // 这个就是为了计数,每次添加两个工作线程
            for (int i = 0; i < pool->maxNum && counter < NUMBER && pool->liveNum < pool->maxNum; ++i){
                if (pool->threadIDs[i] == 0){
                    pthread_create(&pool->threadIDs[i], NULL, worker, pool); // 添加工作线程
                    counter++;
                    pool->liveNum++;
                }
            }
            pthread_mutex_unlock(&pool->mutexPool);
        }

        // 销毁线程
        // 规则:忙的线程*2 < 存活的线程数 && 存活的线程>最小线程数
        // 只涉及读liveNum、minNum共享变量,所以不需要加锁
        if (busyNum * 2 < liveNum && liveNum > pool->minNum){
            pthread_mutex_lock(&pool->mutexPool);
            pool->exitNum = NUMBER;  // 一次性销毁两个线程
            pthread_mutex_unlock(&pool->mutexPool);

            // 让工作的线程自杀,就是在工作线程里让它死去;
            // 当工作线程worker()不工作的时候,都阻塞在条件变量上,所以去唤醒条件变量,每次自杀2个;
            for (int i = 0; i < NUMBER; ++i){
                pthread_cond_signal(&pool->notEmpty);
            }
        }
    }
    return NULL;
}

// 当线程销毁退出的时候,对应数组要置0,下一次可以重新利用;
void threadExit(ThreadPool* pool){
    pthread_t tid = pthread_self();
    for (int i = 0; i < pool->maxNum; ++i){
        if (pool->threadIDs[i] == tid){
            pool->threadIDs[i] = 0;
            printf("threadExit() called, %ld exiting...\n", tid);
            break;
        }
    }
    pthread_exit(NULL);
}
